<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 云筑劳务数据同步 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <!-- 搜索 -->
      <searchData :searchData="searchArr" @search="search"></searchData>
      <!-- 表格 -->
      <a-card :bordered="false">
        <!-- <title-name title="项目列表"></title-name> -->
        <!-- 汇总 -->
        <a-alert :showIcon="true" class="mb12">
          <template slot="message">
            <span style="margin-right: 12px">
              项目总共
              <a>
                <b>{{ total }}</b>
              </a>
              个
            </span>
          </template>
        </a-alert>
        <list-table
          ref="table"
          tableLayout="fixed"
          size="default"
          rowKey="projectId"
          :columns="columns"
          :request="loadData"
          show-size-changer
          show-quick-jumper
          showPagination="auto"
        >
          <template slot="action" slot-scope="text, record">
            <MoreButton>
            <a v-btnPermission="'pm_035_loo_01'" @click="handleManage(record)">查看分包</a>
            <template v-if="record.projectCode">
              <a v-btnPermission="'pm_035_edi_02'" @click="handleOpen(0, record)">同步数据</a>
            </template>
            <a v-btnPermission="'pm_035_edi_03'" @click="handleOpen(1, record)">云筑劳务配置</a>
            </MoreButton>
          </template>
        </list-table>
      </a-card>
    </div>
    <!-- 表单弹窗 -->
    <dialogForm
      ref="dialogForm"
      :api="editModel == 1 ? api : null"
      :visible.sync="visible"
      :rules="rules"
      :editModel="['V', 'E'][editModel]"
      :form="form"
      :customFooter="editModel == 0"
      confirmBtn="保存"
      :headerTitle="['云筑劳务人员信息导入', '云筑劳务信息设置'][editModel]"
      :width="1000"
      :formList="[importList, settingList][editModel]"
      @confirm="submitForm"
    >
      <template v-if="editModel == 0">
        <!-- 导入结果 -->
        <div slot="result" style="margin-top: -3px">
          <template v-if="exportList[0].datas.length > 0 && importStatus == 0">
            <span class="del_btn mr20">同步完成，失败{{ exportList[0].datas.length }}条</span>
            <ExportExcel
              ref="exportExcel"
              class="mb12"
              buttonType="link"
              :export-list="exportList"
              file-name="云筑同步失败数据列表.xlsx"
              button-text="下载失败数据"
            />
            <a-table
              ref="table"
              tableLayout="fixed"
              size="default"
              :scroll="{ y: 350 }"
              rowKey="id"
              :columns="exportList[0].columns"
              :data-source="exportList[0].datas"
              :pagination="false"
            ></a-table>
          </template>
          <span v-else style="color: green">同步完成，导入成功</span>
        </div>
        <!-- 导入按钮 -->
        <a-button slot="footer" :loading="loading" type="primary" @click="submitForm(form)">{{ importBtn }}</a-button>
      </template>
    </dialogForm>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { getYzProject, getYzProjectDetail, importYz, addYzConfig, editYzConfig } from '@/api/project/projects' // api
import DialogForm from '@/components/DialogForm' // 表单弹窗
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import OrgTreeSelect from '@/components/OrgTreeSelect'
import ExportExcel from '@/components/exportExcel/ExportExcel'

const searchArr = [
  // 搜索框
  {
    name: '所属单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
  },
  // {
  //   name: '所属分公司',
  //   type: SelectSubCompany,
  //   valueKey: 'branchCompanyId'
  // },
  // {
  //   name: '项目名称',
  //   type: SelectProject,
  //   valueKey: 'projectId'
  // }
]
const columns = [
  {
    title: '项目名称',
    ellipsis: true,
    width:100,
    dataIndex: 'projectName'
  },
  {
    title: '分公司',
    ellipsis: true,
    width:100,
    dataIndex: 'branchCompanyName'
  },
  {
    title: '云筑项目编号',
    ellipsis: true,
    width:120,
    dataIndex: 'projectCode'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 300,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'employeeSync',
  components: {
    STable,
    DialogForm,
    ExportExcel
  },
  data() {
    return {
      columns, // 表头
      searchArr, // 搜索表单
      api: null, // 表单api
      total: 0, // 项目总数
      loading: false, // 按钮加载控件
      importBtn: '导入信息', // 按钮加载控件
      queryParam: {}, // 查询参数
      visible: false, // 弹窗显隐控件
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getYzProject(requestParameters).then((res) => {
          if (res.data) {
            this.total = res.totalSize
            return res
          }
        })
      },
      importStatus: 0, // 导入状态：0 失败；1 成功
      exportList: [
        {
          columns: [
            {
              dataIndex: 'name',
              title: '姓名'
            },
            {
              dataIndex: 'idCard',
              title: '身份证'
            },
            {
              dataIndex: 'projectName',
              title: '项目名称'
            },
            {
              dataIndex: 'subContractorName',
              title: '分包商'
            },
            {
              dataIndex: 'teamName',
              title: '班组'
            },
            {
              dataIndex: 'positionName',
              title: '职位'
            },
            {
              dataIndex: 'errorReason',
              title: '失败理由'
            }
          ],
          datas: [] // // 导入结果
        }
      ],
      editModel: 0, // 操作类型：0 同步数据；1 云筑劳务配置
      form: {}, // 弹窗表单
      settingList: [
        {
          type: 'BaseInput',
          disabled: true,
          label: '项目名称',
          keyName: 'projectName',
          span: 22
        },
        {
          type: 'BaseInput',
          keyName: 'appId',
          label: 'appid',
          span: 22
        },
        {
          type: 'BaseInput',
          keyName: 'secretKey',
          label: 'secretkey',
          span: 22,
          attrs: {
            maxLength: 50
          }
        },
        {
          type: 'BaseInput',
          keyName: 'projectCode',
          label: '项目编号',
          span: 22
        },
        {
          type: 'BaseInput',
          keyName: 'projectSecretKey',
          label: '项目密钥',
          span: 22,
          attrs: {
            maxLength: 50
          }
        }
      ], // 云筑配置表单列表
      rules: {
        appId: [{ required: true, whitespace: true, message: '请输入appid', trigger: 'change' }],
        secretKey: [{ required: true, whitespace: true, message: '请输入secretkey', trigger: 'change' }],
        projectCode: [{ required: true, whitespace: true, message: '请输入项目编号', trigger: 'change' }],
        projectSecretKey: [{ required: true, whitespace: true, message: '请输入项目密钥', trigger: 'change' }]
      } // 表单校验规则
    }
  },
  computed: {
    // 导入表单列表
    importList() {
      return [
        {
          type: 'BaseInput',
          isEdit: true,
          disabled: true,
          label: '项目名称',
          keyName: 'projectName',
          span: 22
        },
        {
          slot: true,
          label: '信息提示',
          keyName: 'result',
          hidden: this.exportList[0].datas.length === 0 && this.importStatus == 0,
          span: 22
        }
      ]
    }
  },
  methods: {
    /**
     * 人员管理
     */
    handleManage(e) {
      this.$router.push({
        path: '/subcontractors/projectSubcontractors',
        query: {
          projectId: e.projectId
        }
      })
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     * 操作栏
     */
    handleOpen(e, record) {
      this.editModel = e
      this.form = record
      this.api = record.projectCode ? { getDetail: getYzProjectDetail } : null
      if (e === 0) {
        this.exportList[0].datas = []
        this.importBtn = '导入信息'
        this.importStatus = 0
      }
      this.visible = true
    },
    /**
     * 提交表单
     */
    submitForm(e) {
      if (this.editModel == 1) {
        let url = e.id ? editYzConfig : addYzConfig // 请求api
        this.$refs.dialogForm.loading = true
        url(e)
          .then(() => {
            this.$refs.dialogForm.loading = false
            this.$message.success('配置成功')
            this.$refs.table.loadData()
            this.visible = false
          })
          .catch(() => {
            this.$refs.dialogForm.loading = false
          })
      } else {
        this.loading = true
        this.importBtn = '导入中'
        importYz(e)
          .then((res) => {
            this.loading = false
            if (res.code === 200) {
              this.importBtn = '重新导入'
              if (res.data?.length > 0) {
                this.$message.success('导入完成')
                this.exportList[0].datas = res.data
              } else {
                this.importStatus = 1
                this.$message.success('导入成功')
              }
            }
          })
          .catch(() => {
            this.importBtn = '重新导入'
            this.loading = false
          })
      }
    }
  }
}
</script>
